#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2024/01/16 16:07:53
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   程序入口
'''

from init import import_classes, get_classes, Maker
from init import init_chrome_driver

import os
import time
from excel import readParams

import PySimpleGUI as sg


# 初始化数据路径
def init_path(path_db:str=None):
    os.path.exists("db") or os.mkdir("db")
    current_date = time.strftime("%Y%m%d", time.localtime())
    path = os.path.join(os.getcwd(), "db", current_date)
    if not (path_db is None):
        path = os.path.join(path_db, "db", current_date)
    # 创建文件夹
    try:
        os.mkdir(path)
    except FileExistsError:
        print("文件夹已经存在")
    
    return path

def run(instance_path:str, path_db:str, params_file:str):
    # 扫描路径获取模块名
    classNameList = import_classes(instance_path)
    # 加载类名，返回由类字典组成的列表
    classes = get_classes(classNameList)
    print(classes)
    path = init_path(path_db)
    params_list = readParams(params_file)
    driver_path = init_chrome_driver(f"./chromedriver")
    print(driver_path)
    for i, item in enumerate(params_list):
        sg.one_line_progress_meter("爬虫进度", i, len(params_list), '进度')
        print(item['class'])
        item['class'] = classes[item['class'].lower()]
        item['path'] = path
        # Maker(item, driver_path)
        try:
            Maker(item, driver_path)
        except Exception as e:
            print(e)
            continue
